<?php
$shippmentPlanService = new ShippmentPlanService();
$shippmentPlanDetailService = new ShippmentPlanDetailService();
$orderDetailService = new OrderDetailsService();
switch ($action) {
	case "addPlan":
		if($permit == true)
		{
			if(isset($_POST['btn_submit']) && isset($_POST['startDate']) && isset($_POST['containerCode']))
			{
				print_r($_POST);
				$orderID = $_POST['orderID'];
				$shippmentPlanID = null;
				$startDate = $_POST['startDate'];
				$container = $_POST['containerCode'];
				if($_POST['shippment'] == 'newShippment')
				{
					$shippmentData['startDate'] = $startDate;
					$startDateTime = strtotime($startDate);
					$startWeek = date("W", $startDateTime);
					$shippmentData['startWeek'] = $startWeek;
					$shippmentData['container'] = $container;
					$shippmentData['description'] = $_POST['desc'];
					$shippmentPlanDomain = new ShippmentplanDomain($shippmentData);
					$rs = $shippmentPlanService->createShippmentPlan($context, $result, $shippmentPlanDomain);
					if($rs != '' || $rs != null)
					{
						$shippmentPlanID = $rs;
					}
				}
				if($_POST['shippment'] == 'existShippment')
				{
					$shippmentPlanID = $shippmentPlanService->getShippmentPlanIDByStartDateAndContainer($context, $result, $startDate, $container);
				}
				if($shippmentPlanID != '' || $shippmentPlanID != null)
				{
					foreach ($_POST as $key => $value) {
						if(is_numeric($key))
						{
							$shippmentPlanDetailDomain = $shippmentPlanDetailService->getTheLastSPDetailByOrderIDAndArticleID($context, $result, $orderID, $key);
							if($shippmentPlanDetailDomain != null || $shippmentPlanDetailDomain != '')
							{
								$oldRemainQuantity = $shippmentPlanDetailDomain->getRemainQuantity();
							}
							else
							{
								$orderDetailsDomain = $orderDetailService->getOrderDetailByOrderIDAndArticleID($context, $result, $orderID, $key);
								$oldRemainQuantity = $orderDetailsDomain->getQuantity();

							}
							if($value <= $oldRemainQuantity)
							{
								$newRemainQuantity = $oldRemainQuantity - $value;
								$shippmentDetailData['shippmentID'] = $shippmentPlanID;
								$shippmentDetailData['orderID'] = $orderID;
								$shippmentDetailData['articleID'] = $key;
								$shippmentDetailData['shipQuantity'] = $value;
								$shippmentDetailData['remainQuantity'] = $newRemainQuantity;
								$shippmentDetailDomain = new ShippmentplandetailsDomain($shippmentDetailData);
								$shippmentPlanDetailService->createShippmentPlanDetail($context, $result, $shippmentDetailDomain);
								header("Location:index.php?func=ship&opt=addPlan&id=".$orderID);
							}
						}
					}
				}
			}
			else
			echo "Please choose start date and input container code!";
		}
		else
		header("Location:index.php?func=dash");
		break;
			
	default:
		echo "khong co tinh nang nay";
		break;
}
?>